package com.yft.data.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.yft.data.dao.PublicDao;
import com.yft.data.util.DataConfig;
import com.yft.data.util.StringUtil;

/**
 * @author Ruibron
 * 
 */
@Service
public class DataService {
	private Logger logger = Logger.getLogger(DataService.class);
	@Autowired
	private PublicDao publicDao;
//	@Autowired
//	private MongoOperations mongoTemplate;
	@Autowired
	private BlackListService blackListService;
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 获取房源列表
	 * 
	 * @param pageNo
	 *            分页页数
	 * @param pageSize
	 *            分页size
	 * @param type
	 * @param cityid
	 * @param area
	 * @param search
	 * @param dateType
	 * @param priceType
	 * @param areaType
	 * @param roomType
	 * @return 房源池列表
	 */
	public List<Map<String, Object>> getFanYuanListFromMG(int pageno, int pagesize,
			int type, int cityid, String area, String search, int datetype,
			int pricetype, int spacetype, int roomtype) {
		Query q = getMongoQuery(type, cityid, area, search, datetype,
				pricetype, spacetype, roomtype);
		q.skip(pageno*pagesize);
		q.limit(pagesize);
		//List<User> users = mongoTemplate.find(new Query(new Criteria("name").regex(".*?"+"张"+".*")).limit(9), User.class); 
		return null;
	
	}
	/**
	 * 设置黑名单
	 * 
	 * @return
	 */
	@CacheEvict(value="blacklist", allEntries=true)
	public int setBlackList() {
		// 查询内容表，并更新黑名单表
		int num = 0;
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1); // 得到前一个月
		long date = calendar.getTimeInMillis();
		String datestr;
		datestr = df.format(new Date(date));
		System.out.println(datestr);
		StringBuffer sb = new StringBuffer();
		sb.append("select hs.person,hs.phone,sr.parent_id from tbl_hs as hs , tbl_source as sr  ");
		sb.append("where hs.date>'" + datestr+"'");
		sb.append(" and hs.source_id=sr.id group by hs.phone,sr.parent_id HAVING count(phone)>5");
		String sql = sb.toString();
		//logger.debug(sql);
		List<Map<String, Object>> list = publicDao.getObjectList(sql);
		List<String> blacklist = blackListService.getBlackList();
		List<String> sqllist = new ArrayList<String>();
		if(list.isEmpty())
		{
			return num;
		}
		for (Map<String, Object> map : list) {
			this.dealPhone(map);
			String phone = ((String) map.get("phone")).trim();
			if(phone.equals("")&&map.containsKey("imgUrl"))
			{
				phone = ((String) map.get("imgUrl")).trim();
			}
			//System.out.println(phone);
			if (!blacklist.contains(phone)&&!phone.equals("")) {
				StringBuffer sb2 = new StringBuffer();
				sb2.append("insert into blacklist(phone) values('");
				sb2.append(phone + "')");
				sqllist.add(sb2.toString());
				//System.out.println(sb2.toString());
			}
		}
		if(!sqllist.isEmpty())
		{
			int[] nums = publicDao
					.batchUpdate(sqllist.toArray(new String[sqllist.size()]));
			num = nums.length;
		}
		return num;
	}

	/**
	 * 获取房源列表
	 * 
	 * @param pageNo
	 *            分页页数
	 * @param pageSize
	 *            分页size
	 * @param type
	 * @param cityid
	 * @param area
	 * @param search
	 * @param dateType
	 * @param priceType
	 * @param areaType
	 * @param roomType
	 * @return 房源池列表
	 */
	public List<Map<String, Object>> getFanYuanList(int pageno, int pagesize,
			int type, int cityid, String area, String search, int datetype,
			int pricetype, int spacetype, int roomtype) {
		StringBuffer sb = new StringBuffer();
		sb.append("select id,date as createTime,title,space,price,type,phone,");
		sb.append("date,");
		sb.append("area,district,");
		sb.append("url,building,roomType,floor,cityid,src ");
		StringBuffer sb2 = dealSqlWhere(type, cityid, area, search, datetype,
				pricetype, spacetype, roomtype);
		sb.append(sb2);
		sb.append("order by date desc ");
		sb.append("LIMIT ");
		sb.append((pageno - 1) * pagesize);
		sb.append(", " + pagesize);
		String sql = sb.toString();
		//System.out.println(sql);
		//logger.debug(sql);
		//
		Date date = dealDateType(datetype);
		//String datestr = df.format(date);
		List<Map<String, Object>> list = publicDao.getObjectList(sql,date);
		// System.out.println(list.size());
		list = dealList(list);
		return list;
	}

	/**
	 * 查询count
	 * 
	 * @param type
	 * @param cityid
	 * @param area
	 * @param search
	 * @param datetype
	 * @param pricetype
	 * @param spacetype
	 * @param roomtype
	 * @return
	 */
	public int getCountMongo(int type, int cityid, String area, String search,
			int datetype, int pricetype, int spacetype, int roomtype) {
		int i = 0;
		Query q = getMongoQuery(type, cityid, area, search, datetype,
				pricetype, spacetype, roomtype);
		//query.fields().exclude("qq");  
        //query.sort().on("name", Order.ASCENDING);  
		//System.out.println(q.toString());
		//System.out.println(mongoTemplate.count(q, "hs"));
//		i = (int) mongoTemplate.count(q, "hs");
		return i; 
	}
	private Query getMongoQuery(int type, int cityid, String area,
			String search, int datetype, int pricetype, int spacetype,
			int roomtype) {
		Query q = new Query();
		List<Criteria> orList = new ArrayList<Criteria>();
		if(type!=0)
		{
			q.addCriteria(Criteria.where("type").is(type));
		}
		DataConfig.getPriceTypeMongo(q,pricetype);
		DataConfig.getSpaceTypeMongo(q,spacetype);
		DataConfig.getRoomTypeMongo(q,roomtype,orList);
		DataConfig.getDateTypeMongo(q,datetype);
		q.addCriteria(Criteria.where("cityid").is(cityid));
		if(!area.equals(""))
		{
			Criteria c = new Criteria("area").regex(".*?"+area+".*");
//			c.orOperator(
//					new Criteria("area").regex(".*?"+area+".*"),
//					new Criteria("district").regex(".*?"+area+".*"),
//					new Criteria("address").regex(".*?"+area+".*")
//					);
			q.addCriteria(c);
		}
		if(!search.equals(""))
		{
			q.addCriteria(new Criteria("description").regex(".*?"+search+".*"));
		}
		return q;
	}
	/**
	 * 查询count
	 * 
	 * @param type
	 * @param cityid
	 * @param area
	 * @param search
	 * @param datetype
	 * @param pricetype
	 * @param spacetype
	 * @param roomtype
	 * @return
	 */
	public int getCount(int type, int cityid, String area, String search,
			int datetype, int pricetype, int spacetype, int roomtype) {
		StringBuffer sb = new StringBuffer();
		sb.append("select count(id) ");
		StringBuffer sb2 = dealSqlWhere(type, cityid, area, search, datetype,
				pricetype, spacetype, roomtype);
		sb.append(sb2);
		
		String sql = sb.toString();
		logger.debug(sql);
		Date date = dealDateType(datetype);
		//System.out.println(date);
		return publicDao.getCount(sql,date);
	}
	/**
	 * 根据id获取详细信息
	 * 
	 * @param infoid
	 * @return
	 */
	public Map<String, Object> getFanYanDetail(int infoid) {
		StringBuffer sb = new StringBuffer();
		sb.append("select id,DATE_FORMAT(date,'%Y-%m-%d %T') as date,fixture,remark,cityid,readCount,phone,imgUrl,area,property,type,url,title,price,space,floor,person,fitment,address,building,direction,district,pay_type,roomType,src ");
		sb.append("from tbl_hs ");
		sb.append("where ");
		sb.append("id = " + infoid);
		String sql = sb.toString();
		List<Map<String, Object>> list = publicDao.getObjectList(sql);
		Map<String, Object> map = list.get(0);
		dealSrc(map);
		dealPhone(map);
		// dealArea(map);
		return map;
	}
	/**
	 * 拼写查询条件
	 * 
	 * @param type
	 * @param cityid
	 * @param area
	 * @param search
	 * @param datetype
	 * @param pricetype
	 * @param spacetype
	 * @param roomtype
	 * @return
	 */
	private StringBuffer dealSqlWhere(int type, int cityid, String area,
			String search, int datetype, int pricetype, int spacetype,
			int roomtype) {
		StringBuffer sb2 = new StringBuffer();
		sb2.append("from tbl_hs ");
		sb2.append("where ");
		sb2.append(DataConfig.getPriceType(pricetype));
		sb2.append(DataConfig.getSpaceType(spacetype));
		sb2.append("cityid =" + cityid + " and ");
		sb2.append("date>? and ");
		if (type != 0) {
			sb2.append("type = " + String.valueOf(type) + " and ");
		}

		sb2.append(DataConfig.getRoomType(roomtype));
		
		if (!area.trim().equals("")) {
			sb2.append("(area like '%" + area + "%' or ");
			sb2.append("district like '%" + area + "%' or ");
			sb2.append("address like '%" + area + "%') and ");
		}
		if (!search.trim().equals("")) {
			sb2.append("description like '%" + search + "%' and ");
		}
		sb2.append(" 1=1 ");
		return sb2;
	}

	/**
	 * 处理数据格式
	 * 
	 * @param list
	 * @return
	 */
	private List<Map<String, Object>> dealList(List<Map<String, Object>> list) {
		List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
		List<String> blacklist = blackListService.getBlackList();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = list.get(i);
			// list.remove(i);
			dealSrc(map);
			dealCreateTime(map);
			dealArea(map);
			dealPhone(map);
			dealDate(map);
			dealDiffTime(map);
			//公共黑名单过滤
			if(!blacklist.contains(map.get("phone"))&&!blacklist.contains(map.get("imgUrl")))
			{
				list2.add(map);
			}
		}
		return list2;
	}
	
	private void dealCreateTime(Map<String, Object> map) {
		Date date = (Date) map.get("createTime");
		String datestr = sf.format(date);
		map.remove("createTime");
		map.put("createTime", datestr);
		
	}

	private void dealDate(Map<String, Object> map) {
		Date date = (Date) map.get("date");
		String datestr = df.format(date);
		map.remove("date");
		map.put("date", datestr);
	}



	/**
	 * 增加读取次数
	 * 
	 * @param infoid
	 * @return
	 */
	public int updateReadCount(int infoid) {
		StringBuffer sb = new StringBuffer();
		sb.append("update tbl_hs set readCount= readCount + 1 where id = "
				+ infoid);
		String sql = sb.toString();
		return publicDao.update(sql);
	}



	/**
	 * 如果没有区域，就用小区替换
	 * 
	 * @param map
	 */
	private void dealArea(Map<String, Object> map) {
		String area = (String) map.get("area");
		String district = (String) map.get("district");
		if (area != null && !area.equals("")) {
			map.remove("district");
			return;
		} else if (district != null && !district.equals("")) {
			map.remove("district");
			map.put("area", district);
		}

	}

	/**
	 * 去掉后面的文字
	 * 
	 * @param map
	 */
	private void dealSrc(Map<String, Object> map) {
		String srcFull = (String) map.get("src");
		String src = srcFull.split("_")[0];
		map.put("src", src);
	}

	/**
	 * 电话去掉html标签
	 * 
	 * @param map
	 */
	private void dealPhone(Map<String, Object> map) {
		String phoneHtml = (String) map.get("phone");
		if (phoneHtml != null && !phoneHtml.equals("")) {
			String src = StringUtil.isIncludeImg(phoneHtml);
			// 不包含图片
			if (src.equals("")) {
				String phone = StringUtil.filterAllTag(phoneHtml);
				map.put("phone", phone);
			}
			// 包含图片
			else {
				// phone设置为空，imgUrl设置为src
				map.remove("imgUrl");
				map.remove("phone");
				map.put("phone", "");
				map.put("imgUrl", src);
			}

		}

	}
	
	/**
	 * 处理时间间隔
	 * 
	 * @param map
	 */
	private void dealDiffTime(Map<String, Object> map) {
		String date = (String) map.get("date");
		// System.out.println(date);
		// System.out.println(date.toString().split(".").length);
		map.remove("date");
		if (!date.equals("") && date != null) {
			String diffTime = StringUtil.getCompareTime(date);
			map.put("diffTime", diffTime);
		}
	}
	
	/**
	 * 根据时间类型返回时间
	 * @param datetype
	 * @return
	 */
	private Date dealDateType(int datetype) {
		Date d = new Date();
		switch (datetype) {
		case 1:
			return StringUtil.getDateBefore(d, 1);
		case 2:
			return StringUtil.getDateBefore(d, 3);
		case 3:
			return StringUtil.getDateBefore(d, 7);
		case 4:
			return StringUtil.getDateBefore(d, 30);
		}
		return StringUtil.getDateBefore(d, 3);
	}
}
